/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.swirrel.installer;

import java.awt.Adjustable;
import java.awt.Component;
import java.awt.Scrollbar;
import java.awt.event.AdjustmentListener;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Arrays;
import javax.swing.JScrollBar;
import org.swirrel.annotation.AdjustmentValueChanged;
import org.swirrel.listener.SwirrelAdjustmentListener;
import org.swirrel.util.MethodCall;

/**
 *
 * @author Gronau
 */
public class AdjustmentListenerInstaller extends AbstractListenerInstaller implements SwirrelListenerInstaller {
    public AdjustmentListenerInstaller() {
        super(Arrays.<Class<? extends Annotation>>asList(AdjustmentValueChanged.class),
                Arrays.<Class<?>>asList(Adjustable.class));
    }

    public boolean isListenerAlreadySet(Object obj) {
       AdjustmentListener[] adjustmentListeners =
               (obj instanceof JScrollBar) ? ((JScrollBar) obj).getAdjustmentListeners()
               : (obj instanceof Scrollbar) ? ((Scrollbar) obj).getAdjustmentListeners()
               : new AdjustmentListener[0]; //give up, as Adjustable has no such method
        for (AdjustmentListener al : adjustmentListeners) {
            if (al instanceof SwirrelAdjustmentListener) {
                return true;
            }
        }
        return false;
    }

    public void registerListener(Field field, Component comp, java.util.List<MethodCall> methodCalls) throws IllegalAccessException {
        Object obj = field.get(comp);
        AdjustmentListener al = new SwirrelAdjustmentListener(methodCalls.get(0));
         ((Adjustable) obj).addAdjustmentListener(al);
    }
}
